package com.hzt.agprosaleplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzt.agprosaleplatform.entity.Good;
import com.hzt.agprosaleplatform.entity.Order;
import com.hzt.agprosaleplatform.entity.User;
import com.hzt.agprosaleplatform.mapper.GoodsMapper;
import com.hzt.agprosaleplatform.mapper.OrderMapper;
import com.hzt.agprosaleplatform.mapper.UserMapper;
import com.hzt.agprosaleplatform.service.AdminDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AdminDashboardServiceImpl implements AdminDashboardService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Map<String, Object> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();

        // 获取用户总数
        long totalUsers = userMapper.selectCount(null);
        stats.put("totalUsers", totalUsers);
        
        // 获取订单总数
        long totalOrders = orderMapper.selectCount(null);
        stats.put("totalOrders", totalOrders);
        
        // 获取商品总数
        long totalGoods = goodsMapper.selectCount(null);
        stats.put("totalGoods", totalGoods);
        
        // 计算总营收（所有订单金额之和）
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
        orderWrapper.select("IFNULL(SUM(total_amount), 0) as totalRevenue");
        List<Map<String, Object>> revenueResult = orderMapper.selectMaps(orderWrapper);
        double totalRevenue = revenueResult.isEmpty() ? 0 : 
            ((Number) revenueResult.get(0).get("totalRevenue")).doubleValue();
        stats.put("totalRevenue", totalRevenue);

        // 按角色统计用户数
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.select("role", "COUNT(*) as count");
        userWrapper.groupBy("role");
        
        List<Map<String, Object>> roleStats = userMapper.selectMaps(userWrapper);
        stats.put("userByRole", roleStats);

        return stats;
    }
    
    @Override
    public Map<String, Object> getRecentOrdersStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取近7天的日期
        List<String> last7Days = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 6; i >= 0; i--) {
            last7Days.add(LocalDate.now().minusDays(i).format(formatter));
        }
        
        // 构造查询条件，获取近7天的订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.apply("DATE(created_date) >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)")
                         .apply("DATE(created_date) <= CURDATE()")
                         .select("DATE(created_date) as orderDate, COUNT(*) as orderCount");
        orderQueryWrapper.groupBy("DATE(created_date)");
        orderQueryWrapper.orderByAsc("DATE(created_date)");
        
        List<Map<String, Object>> orderStats = orderMapper.selectMaps(orderQueryWrapper);
        
        // 处理数据，确保每天都有数据（没有订单的日期显示为0）
        List<Integer> orderCounts = new ArrayList<>();
        Map<String, Integer> orderMap = orderStats.stream()
                .collect(Collectors.toMap(
                    map -> map.get("orderDate").toString(),
                    map -> ((Long) map.get("orderCount")).intValue()
                ));
        
        for (String date : last7Days) {
            orderCounts.add(orderMap.getOrDefault(date, 0));
        }
        
        stats.put("dates", last7Days);
        stats.put("orderCounts", orderCounts);
        
        return stats;
    }
    
    @Override
    public Map<String, Object> getRecentThreeMonthsOrdersStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取近三个月的月份
        List<String> last3Months = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        for (int i = 2; i >= 0; i--) {
            last3Months.add(LocalDate.now().minusMonths(i).format(formatter));
        }
        
        // 构造查询条件，获取近三个月的订单
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.apply("DATE_FORMAT(created_date, '%Y-%m') >= DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 2 MONTH), '%Y-%m')")
                         .apply("DATE_FORMAT(created_date, '%Y-%m') <= DATE_FORMAT(CURDATE(), '%Y-%m')")
                         .select("DATE_FORMAT(created_date, '%Y-%m') as orderMonth, COUNT(*) as orderCount");
        orderQueryWrapper.groupBy("DATE_FORMAT(created_date, '%Y-%m')");
        orderQueryWrapper.orderByAsc("DATE_FORMAT(created_date, '%Y-%m')");
        
        List<Map<String, Object>> orderStats = orderMapper.selectMaps(orderQueryWrapper);
        
        // 处理数据，确保每个月都有数据（没有订单的月份显示为0）
        List<Integer> orderCounts = new ArrayList<>();
        Map<String, Integer> orderMap = orderStats.stream()
                .collect(Collectors.toMap(
                    map -> map.get("orderMonth").toString(),
                    map -> ((Long) map.get("orderCount")).intValue()
                ));
        
        for (String month : last3Months) {
            orderCounts.add(orderMap.getOrDefault(month, 0));
        }
        
        stats.put("months", last3Months);
        stats.put("orderCounts", orderCounts);
        
        return stats;
    }
    
    @Override
    public Map<String, Object> getRecentRevenueStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取近7天的日期
        List<String> last7Days = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 6; i >= 0; i--) {
            last7Days.add(LocalDate.now().minusDays(i).format(formatter));
        }
        
        // 构造查询条件，获取近7天的营收
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.apply("DATE(created_date) >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)")
                         .apply("DATE(created_date) <= CURDATE()")
                         .select("DATE(created_date) as orderDate, IFNULL(SUM(total_amount), 0) as revenue");
        orderQueryWrapper.groupBy("DATE(created_date)");
        orderQueryWrapper.orderByAsc("DATE(created_date)");
        
        List<Map<String, Object>> revenueStats = orderMapper.selectMaps(orderQueryWrapper);
        
        // 处理数据，确保每天都有数据（没有订单的日期显示为0）
        List<Double> revenues = new ArrayList<>();
        Map<String, Double> revenueMap = revenueStats.stream()
                .collect(Collectors.toMap(
                    map -> map.get("orderDate").toString(),
                    map -> ((Number) map.get("revenue")).doubleValue()
                ));
        
        for (String date : last7Days) {
            revenues.add(revenueMap.getOrDefault(date, 0.0));
        }
        
        stats.put("dates", last7Days);
        stats.put("revenues", revenues);
        
        return stats;
    }
    
    @Override
    public Map<String, Object> getGoodsStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取商品总数
        long totalGoods = goodsMapper.selectCount(null);
        stats.put("totalGoods", totalGoods);
        
        // 获取最近7天新增商品数
        QueryWrapper<Good> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.apply("DATE(created_date) >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)")
                         .apply("DATE(created_date) <= CURDATE()")
                         .select("DATE(created_date) as goodsDate, COUNT(*) as goodsCount");
        goodsQueryWrapper.groupBy("DATE(created_date)");
        goodsQueryWrapper.orderByAsc("DATE(created_date)");
        
        List<Map<String, Object>> goodsStats = goodsMapper.selectMaps(goodsQueryWrapper);
        
        // 获取近7天的日期
        List<String> last7Days = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 6; i >= 0; i--) {
            last7Days.add(LocalDate.now().minusDays(i).format(formatter));
        }
        
        // 处理数据，确保每天都有数据（没有商品的日期显示为0）
        List<Integer> goodsCounts = new ArrayList<>();
        Map<String, Integer> goodsMap = goodsStats.stream()
                .collect(Collectors.toMap(
                    map -> map.get("goodsDate").toString(),
                    map -> ((Long) map.get("goodsCount")).intValue()
                ));
        
        for (String date : last7Days) {
            goodsCounts.add(goodsMap.getOrDefault(date, 0));
        }
        
        stats.put("dates", last7Days);
        stats.put("goodsCounts", goodsCounts);
        
        return stats;
    }
}